package com.apes.framework.plugin.soe.store.database.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.soe.core.utils.Const;
import com.apes.framework.plugin.soe.metadata.BusinessType;
import com.apes.framework.plugin.soe.store.database.repository.BusinessTypeRepository;
import com.apes.scm.masterdata.enumeration.service.EnumerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("businessTypeService")
public class BusinessTypeService extends DomainService {

    @Autowired
    private Cache cache;

    @Autowired
    BusinessTypeRepository businessTypeRepository;

    @Autowired
    EnumerationService enumerationService;

    public BusinessType save(SimpleRequest simpleRequest) {
        BusinessType businessType = simpleRequest.getO(BusinessType.class);
        //是否聚合根等于true后创建的定义凭证类型才可在业务凭证列表中显示
        //businessType.setAggregateRoot(true);
        return saveAndCache(businessType);
    }

    public BusinessType saveAndCache(String id, String name, boolean isAggregateRoot) {
        BusinessType businessType = getBusinessTypeByCache(id);
        if (businessType != null) return businessType;
        businessType = new BusinessType();
        businessType.setId(id);
        businessType.setName(name);
        businessType.setValid(false);
        businessType.setAggregateRoot(isAggregateRoot);
        return saveAndCache(businessType);
    }

    private BusinessType saveAndCache(BusinessType businessType) {
        businessType = businessTypeRepository.saveAndFlush(businessType);
        cache.put(Const.CACHE_SCENE_BUSINESS_TYPE, businessType.getId(), businessType);
        return businessType;
    }

    public synchronized BusinessType getBusinessTypeByCache(String id) {
        BusinessType businessType = (BusinessType) cache.get(Const.CACHE_SCENE_BUSINESS_TYPE, id);
        if (businessType != null) return businessType;
        businessTypeRepository.findAll().stream().forEach(bt -> {
            cache.put(Const.CACHE_SCENE_BUSINESS_TYPE, bt.getId(), bt);
        });
        businessType = (BusinessType) cache.get(Const.CACHE_SCENE_BUSINESS_TYPE, id);
        return businessType;
    }

}

